/**
 * Created by Administrator on 2016-10-18.
 * 表格
 */
var getStoresTure = false;
$(function () {

    var NAMESPACE = 'myDataGrid';

    function DataGrid(ele, opt) {
        this.$element = $(ele);
        this.settings = $.extend({}, DataGrid.defaults, $.isPlainObject(opt) && opt);
        this.init();
    }

    DataGrid.defaults = {
        //表格元素
        id: "",
        //PageTotal元素
        pageTotalId: null,
        //PageTool元素
        pageToolId: null,
        //请求地址
        url: null,
        //请求方式
        method: "post",
        //表头格式
        columns: null,
        //页显示
        pagesize: 10,
        //初始化数据
        InitializationData: null,
        //页索引
        pageindex: 1,
        //总记录数
        totalcount: null,
        //取合计事件
        getCollection: null,
        //获取数据后回调事件
        getDataEvent: null,
        //选择全部点击事件
        checkAllEvent: null,
        //单独点击选择事件
        checkSingleEvent: null,
        //隐藏选择框，隐藏的时候默认都选上
        hideCheck: false
    };


    DataGrid.prototype = {
        _id: null,
        _op_dataGrid: null,
        _pageTotalId: null,
        _pageToolId: null,
        _getCollection: null,

        _searchData: null,
        _insearging: false,

        constructor: DataGrid,

        init: function () {
            this._id = this.settings.id;
            this._pageTotalId = this.settings.pageTotalId;
            this._pageToolId = this.settings.pageToolId;
            this._searchData = null;
            this._getCollection = this.settings.getCollection;

            _op_dataGrid = this;

            this.create();
            this.bindEvent();
        },

        create: function () {
            //初始化元素
            this.InitializeElement();
            //初始化表头
            this.createTableHead();
            //初始化动态行
            var currentpage = this.getURLPageParam("page");
            this.createTableBody(currentpage);
        },

        bindEvent: function () {
            //分页事件
            if (this._pageToolId != null) {
                this.registerPageToolChage();
            }

            //添加全选全不选事件
            this.registercheckall();
        },

        //初始化元素
        InitializeElement: function () {
            $("#" + this._id).empty().append("<thead><tr></tr></thead><tbody></tbody>");
            if (this._pageTotalId != null) {
                $("#" + this._pageTotalId).html("");
            }
            if (this._pageToolId != null) {
                $("#" + this._pageToolId).empty();
            }
        },

        //循环增加表头
        createTableHead: function () {
            var headcols = this.settings.columns;
            for (var i = 0; i < headcols.length; i++) {
                if (headcols[i].kind == 'ck') {
                    if (this.settings.hideCheck) {
                        $("table[id='" + this._id + "'] thead tr").append("<th width='50px' style='display: none'><input name='chkall' type='checkbox' checked='true'></th>");
                    } else {
                        $("table[id='" + this._id + "'] thead tr").append("<th width='50px'><input name='chkall' type='checkbox'></th>");
                    }
                }else if(headcols[i].title=="99"){//99是产品管理价格定义的title
                    var titleHtml ="<span style='margin-top: 10px !important;padding: 10px !important;vertical-align: middle;text-align: center;font-weight: bold;color: #333;font-size: 15px'>产品价格定义</span>"+"&nbsp;&nbsp;" +"<div style='margin-top: 5px' class='btn-group' >"+
                    "<button type='button' class='btn btn-default' id='centerList'>无</button>"+
                        "<button type='button' id='managerList' class='btn btn-default dropdown-toggle' data-toggle='dropdown'>"+
                        "<span class='caret'></span>"+
                        "</button>"+
                        "<ul class='dropdown-menu' role='menu' id='centerLists'>"+
                        "</ul>"+
                        "</div>"
                    $("table[id='" + this._id + "'] thead tr").append(titleHtml);
                } else {
                    $("table[id='" + this._id + "'] thead tr").append("<th>" + headcols[i].title + "</th>");
                }
            }
        },

        //循环添加行
        createTableBody: function (pagenumber) {
            var columns = _op_dataGrid.settings.columns;
            // var adata = {};
            // if (_op_dataGrid._searchData != null) {
            //     adata = _op_dataGrid._searchData;
            // }
            var adata = {};
            var pageData = {
                pageIndex: pagenumber,
                pageSize: _op_dataGrid.settings.pagesize
            };
            if (_op_dataGrid._searchData != null) {
                adata = {
                    "searchData":JSON.stringify(_op_dataGrid._searchData),
                    "page": JSON.stringify(pageData)
                };
            } else if(_op_dataGrid.settings.InitializationData != null){
                adata = {
                    "page": JSON.stringify(pageData)
                };
                for (var j = 0; j <_op_dataGrid.settings.InitializationData.length; j++) {
                    adata[_op_dataGrid.settings.InitializationData[j].attribute] = _op_dataGrid.settings.InitializationData[j].attributeValue;
                }
            }else {
                adata = {
                    "page": JSON.stringify(pageData)
                };
            }
            var json = this.getAjaxData(_op_dataGrid.settings.url, adata);
            // console.log(json);
            var rowsdata = "";

            _op_dataGrid.settings.totalcount = json.total;
            if (this._pageTotalId != null) {
                $("#" + this._pageTotalId).html(_op_dataGrid.settings.totalcount);
            }
            var colspanlLength =  columns.length;
            // console.log(json);
            if (json.list.length == 0) {
                rowsdata += "<tr><th  colspan=\"" + colspanlLength + "\"><h3>暂时没有数据</h3></th></tr>"
            } else {

                for (var i = 0; i < json.list.length; i++) {

                    rowsdata += "<tr>";

                    for (var colindex = 0; colindex < columns.length; colindex++) {
                            var dataValue;
                            if (columns[colindex].conmethod != "") {
                                //根据字符串调用对应的方法，apply必须传数组
                                dataValue = json.list[i][columns[colindex].field];
                                var convertmethod = columns[colindex].conmethod;
                                var fn;
                                if (columns[colindex].region == 0) {
                                    fn = this[convertmethod];
                                } else {
                                    fn = window[convertmethod];
                                }
                                if (typeof fn === 'function') {
                                    //第一个参数为当前属性对应的值，第二个参数为当前记录，第三个参数为当前序号 利于扩展
                                    dataValue = fn.apply(this, [dataValue, json.list[i], i]);
                                }
                            } else {
                                dataValue = json.list[i][columns[colindex].field];
                            }
                            rowsdata += '<td>' + dataValue + '</td>';

                    }

                    rowsdata += "</tr>";
                }
            }

            $("table[id='" + this._id + "'] tbody").empty().append(rowsdata);

            //if (_op_dataGrid._searchData != null) {
            //    _op_dataGrid.registerPageToolChage();
            //}
        },

        //取 page参数，不知道怎么写正则表达式
        //http://localhost:8000/user-pirceList.html?id=2016091591&type=%u7EA2%u5305#page=1
        getURLPageParam: function (name) {
            var page = "";

            var regarray = window.location.href.split("#");
            for (var i = 0; i < regarray.length; i++) {
                if (regarray[i].substring(0,5) == "page=") {
                    page = regarray[i];
                    break;
                }
            }

            if (page=="") {
                return 1;
            } else {
                return parseInt(page.split("=")[1]);
            }
        },

        //获取数据
        getAjaxData: function (url, params) {
            var result;
            $.ajax({
                url: url,
                //改为同步方式
                async: false,
                type: _op_dataGrid.settings.method,
                data: params,
                //data: jsonParams,
                dataType: 'json',
                //contentType : 'application/json; charset=UTF-8',
                success: function (data) {
                    // console.log(data);
                    if(data.data.detail){
                        if (_op_dataGrid.settings.getCollection != null) _op_dataGrid.settings.getCollection(data.data.collection);
                        result = data.data.detail;
                    }else{
                        result = data.data;
                    }
                    // console.log(result);
                    if (_op_dataGrid.settings.getDataEvent != null) _op_dataGrid.settings.getDataEvent(result);
                }
            });
            return result;
        },

        //注册分页事件
        registerPageToolChage: function () {
            if (!this._insearging) {
                var currentpage = this.getURLPageParam("page");
            } else {
                var currentpage = 1;
            }

            if (this._pageToolId != null) {
                $("#" + this._pageToolId).empty();
                $("#" + this._pageToolId).Paging({
                    current:currentpage,
                    pagesize: _op_dataGrid.settings.pagesize,
                    count: _op_dataGrid.settings.totalcount,
                    callback: function (page, size, count) {
                        _op_dataGrid.settings.pageindex = page;
                        _op_dataGrid.createTableBody(page);
                    }
                });
            }
        },

        //添加全选全不选事件
        registercheckall: function () {
            //添加全选全不选事件
            $("input[name='chkall']").click(function () {
                if (this.checked) {
                    $("input[name='chk']").each(function () {
                        $(this).prop("checked", true);
                    });
                } else {
                    $("input[name='chk']").each(function () {
                        $(this).prop("checked", false);
                    });
                }

                if (_op_dataGrid.settings.checkAllEvent != null) _op_dataGrid.settings.checkAllEvent();
            });

            $("input[name='chk']").click(function () {
                if (_op_dataGrid.settings.checkSingleEvent != null) _op_dataGrid.settings.checkSingleEvent();
            });
        },
        //表格行的序号
        getRecordIndex: function () {
            return arguments[2] + 1;
        },

        //时间格式化
        getTime: function () {
            var ts = arguments[0] || 0;
            var t, y, m, d, h, i, s;
            t = ts ? new Date(ts) : new Date();
            y = t.getFullYear();
            m = t.getMonth() + 1;
            d = t.getDate();
            h = t.getHours();
            i = t.getMinutes();
            s = t.getSeconds();
            // 可根据需要在这里定义时间格式
            return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' ' + (h < 10 ? '0' + h : h) + ':' + (i < 10 ? '0' + i : i) + ':' + (s < 10 ? '0' + s : s);
        },
        //获取空字符串
        getNullStr: function () {
            var ts = arguments[0] || "";
            return ts;
        },

        //获取空数字
        getNullNumber: function () {
            var ts = arguments[0] || 0;
            return ts;
        },

        //获取空日期var tenTime = order.contractbegintime.substring(0, 10);
        getNullDateTime: function () {
            var ts = arguments[0];
            var dt = "";
            //console.log(ts);
            if (ts != null) {
                if(!isNaN(ts)){
                    //alert("是数字");
                    dt = _op_dataGrid.getTime(ts);
                }else{
                    //alert("不全是数字");
                    if(ts.length>10){
                        dt = ts.substring(0,19);
                    }else {
                        dt = ts.substring(0,10);
                    }

                }

            }
            return dt;
        },
//获取订单状态
        getOrderStatus: function () {
            var status = arguments[0] || 0;
            var stateStr = "";
            switch (status) {
                case 0:
                    stateStr = "<div style='cursor: default;font-size: 12px;font-weight: normal' type='button' class='label label-info'>待 受 理</div>";
                    break;
                case 1:
                    stateStr = "<div style='cursor: default;font-size: 12px;font-weight: normal'' type='button' class='label label-warning'>已 受 理</div>";
                    break;
                case 2:
                    stateStr = "<div style='cursor: default;font-size: 12px;font-weight: normal'' type='button' class='label label-success'>已 完 成</div>";
                    break;
                case 3:
                    stateStr = "<div style='cursor: default;font-size: 12px;font-weight: normal'' type='button' class='label label-danger'>待 审 核</div>";
                    break;
                case 4:
                    stateStr = "<div style='cursor: default;;font-size: 12px;font-weight: normal'' type='button' class='label label-default'>已 关 闭</div>";
                    break;
            }
            return stateStr;
        },
        //测试方法 ，网页上调用方式 $("#testMyGrid").grid("testAlert", data);
        testAlert: function (data) {
            alert(data.name);
        },

        //搜索，data由网页端传入json格式
        search: function (data) {
            _op_dataGrid._insearging = true;
            _op_dataGrid._searchData = data;
            _op_dataGrid.createTableBody(1);
            _op_dataGrid.registerPageToolChage();
            _op_dataGrid._insearging = false;
        },

        //取消搜索
        cancelSearch: function () {
            _op_dataGrid._searchData = null;
            _op_dataGrid.createTableBody(1);
            _op_dataGrid.registerPageToolChage();
        },

        //获取选择的数据，data为固定json格式，selvalue为选择的id列表，calcvalue为选择的合计值
        //使用方法
        // var tmpdata = {
        //     selvalue:"",
        //     calcvalue:0
        // };
        // $("#testMyGrid").grid("getcheckdata", tmpdata);
        getcheckdata: function (data) {
            //console.log(data);
            $('input[name="chk"]:checked').each(function (i) {
                if (data.selvalue == "") {
                    data.selvalue = $(this).attr("value")
                } else {
                    data.selvalue = data.selvalue + "," + $(this).attr("value");
                }

                var dmoney = 0;

                if ($(this).attr("calcvalue") == null) {
                    dmoney = 0;
                } else if ($(this).attr("calcvalue") == "") {
                    dmoney = 0;
                } else {
                    dmoney = parseFloat($(this).attr("calcvalue"));
                }

                data.calcvalue += dmoney;
            });

            return data;
        }

    };

    $.fn.grid = function (option) {
        var args = [].slice.call(arguments, 1);

        return this.each(function () {
            var $this = $(this);
            var data = $this.data(NAMESPACE);
            var options;
            var fn;

            if (!data) {
                if (/destroy/.test(option)) {
                    return;
                }

                options = $.extend({}, $this.data(), $.isPlainObject(option) && option);
                $this.data(NAMESPACE, (data = new DataGrid(this, options)));
            }

            if (typeof option === 'string' && $.isFunction(fn = data[option])) {
                fn.apply(data, args);
            }
        });

        // var grid = new dataGrid(this, options);
        // return this.each(function () {
        //     grid.init();
        // });
    };
    $.fn.grid.Constructor = DataGrid;
});